package com.sun.huazhi.aitaskservice.service.impl;

import com.sun.huazhi.aitaskservice.DTO.request.CreateVideoRequest;
import com.sun.huazhi.aitaskservice.DTO.response.VideoTaskResponse;
import com.sun.huazhi.aitaskservice.common.config.PythonApiProperties;
import com.sun.huazhi.aitaskservice.common.mq.RabbitMQConfig;
import com.sun.huazhi.aitaskservice.dao.entity.VideoTaskMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

@Component
public class VideoTaskConsumer {

    @Autowired
    private WebClient webClient;

    @Autowired
    @Qualifier("pythonApiProperties")
    private PythonApiProperties apiProps;

    // Redis 或数据库服务保存任务状态
    @Autowired
    private VideoTaskStoreService taskStoreService;

    @RabbitListener(queues = RabbitMQConfig.VIDEO_QUEUE)
    public void handleTask(VideoTaskMessage msg) {
        taskStoreService.savePending(msg.getTaskId());

        webClient.post()
                .uri(apiProps.getUrl() + "/create-video")
                .bodyValue(new CreateVideoRequest(msg.getTheme(), msg.getDescription(), msg.getDuration()))
                .retrieve()
                .bodyToMono(VideoTaskResponse.class)
                .doOnNext(response -> taskStoreService.saveResult(msg.getTaskId(), response))
                .subscribe();
    }
}
